package com.pay.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OSSUnit {

	// 阿里云API的内或外网域名 meibaxiu.
	private static String ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
	// 阿里云API的密钥Access Key ID
	private static String ACCESS_KEY_ID = "VGf6AgYguslCSe77";
	// 阿里云API的密钥Access Key Secret
	private static String ACCESS_KEY_SECRET = "sXb8lEmOdDDHzNpyvX9aS7JRBYeY1E";
	// 阿里云存储的空间名称
	private static String bucketName = "meibaxiu";

	/**
	 * 获取阿里云OSS客户端对象
	 */
	public static final OSSClient getOSSClient() {
		OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		return client;
	}

	/**
	 * 新建Bucket --Bucket权限:私有
	 * 
	 * @param bucketName
	 *            bucket名称
	 * @return true 新建Bucket成功
	 */
	public static final boolean createBucket(OSSClient client, String bucketName) {
		Bucket bucket = client.createBucket(bucketName);
		return bucketName.equals(bucket.getName());
	}

	/**
	 * 删除Bucket
	 * 
	 * @param bucketName
	 *            bucket名称
	 */
	public static final void deleteBucket(OSSClient client, String bucketName) {
		client.deleteBucket(bucketName);
	}

	/**
	 * 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代
	 * 
	 * @param client
	 *            OSS客户端
	 * @param file
	 *            上传文件
	 * @param bucketName
	 *            bucket名称
	 * @param diskName
	 *            上传文件的目录 --bucket下文件的路径
	 * @return String
	 */
	@SuppressWarnings("unused")
	public static final String uploadObject2OSS(OSSClient client, File file, String diskName) {
		String resultUrl = null;
		try {
			FileInputStream is = new FileInputStream(file);
			String fileName = file.getName();
			Long fileSize = file.length();
			// 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
			// 上传文件
			PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
			// 解析结果 唯一MD5数字签名
			String resultStr = putResult.getETag();

			resultUrl = OssImgUtil.getImgURl(diskName + file.getName());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		return resultUrl;
	}

	/**
	 * 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代
	 * 
	 * @param client
	 *            OSS客户端
	 * @param file
	 *            上传文件
	 * @param bucketName
	 *            bucket名称
	 * @param diskName
	 *            上传文件的目录 --bucket下文件的路径
	 * @return String
	 */
	@SuppressWarnings("unused")
	public static final String uploadObject2OSS(OSSClient client, InputStream is, String diskName) {
		String resultUrl = null;
		try {
			// FileInputStream is = new FileInputStream(file);
			String fileName = System.currentTimeMillis() + ".jpg";
			Long fileSize = (long) is.available();
			// 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("inline;filename=" + fileName);
			// metadata.setContentDisposition("filename/filesize=" + fileName +
			// "/" + "Byte.");
			// 上传文件
			PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
			// 解析结果 唯一MD5数字签名
			String resultStr = putResult.getETag();

			resultUrl = OssImgUtil.getImgURl(diskName + fileName);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultUrl;
	}

	/**
	 * 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代
	 * 
	 * @param client
	 *            OSS客户端
	 * @param file
	 *            上传文件
	 * @param bucketName
	 *            bucket名称
	 * @param diskName
	 *            上传文件的目录 --bucket下文件的路径
	 * @return String 文件URL
	 */
	@SuppressWarnings("unused")
	public static final String uploadObject2OSS(OSSClient client, MultipartFile file, String diskName) {
		String resultUrl = null;
		try {
			InputStream is = file.getInputStream();
			String fileName = file.getOriginalFilename();
			// 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("inline;filename=" + fileName);
			// 上传文件
			PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
			// 解析结果 唯一MD5数字签名
			String resultStr = putResult.getETag();

			resultUrl = OssImgUtil.getImgURl(diskName + file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		return resultUrl;
	}

	/**
	 * 根据key获取OSS服务器上的文件输入流
	 * 
	 * @param client
	 *            OSS客户端
	 * @param bucketName
	 *            bucket名称
	 * @param diskName
	 *            文件路径
	 * @param key
	 *            Bucket下的文件的路径名+文件名
	 */
	public static final InputStream getOSS2InputStream(OSSClient client, String bucketName, String diskName,
			String key) {
		OSSObject ossObj = client.getObject(bucketName, diskName + key);
		return ossObj.getObjectContent();
	}

	/**
	 * 根据key删除OSS服务器上的文件
	 * 
	 * @param client
	 *            OSS客户端
	 * @param bucketName
	 *            bucket名称
	 * @param diskName
	 *            文件路径
	 * @param key
	 *            Bucket下的文件的路径名+文件名
	 */
	public static void deleteFile(OSSClient client, String diskName, String key) {
		client.deleteObject(bucketName, diskName + key);
	}

	/**
	 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
	 * 
	 * @param fileName
	 *            文件名
	 * @return 文件的contentType
	 */
	/*
	 * public static final String getContentType(String fileName) { String
	 * fileExtension = fileName.substring(fileName.lastIndexOf(".")); if
	 * ("bmp".equalsIgnoreCase(fileExtension)) return "image/bmp"; if
	 * ("gif".equalsIgnoreCase(fileExtension)) return "image/gif"; if
	 * ("jpeg".equalsIgnoreCase(fileExtension) ||
	 * "jpg".equalsIgnoreCase(fileExtension) ||
	 * "png".equalsIgnoreCase(fileExtension)) return "image/jpeg"; if
	 * ("html".equalsIgnoreCase(fileExtension)) return "text/html"; if
	 * ("txt".equalsIgnoreCase(fileExtension)) return "text/plain"; if
	 * ("vsd".equalsIgnoreCase(fileExtension)) return "application/vnd.visio";
	 * if ("ppt".equalsIgnoreCase(fileExtension) ||
	 * "pptx".equalsIgnoreCase(fileExtension)) return
	 * "application/vnd.ms-powerpoint"; if
	 * ("doc".equalsIgnoreCase(fileExtension) ||
	 * "docx".equalsIgnoreCase(fileExtension)) return "application/msword"; if
	 * ("xml".equalsIgnoreCase(fileExtension)) return "text/xml"; return
	 * "text/html"; }
	 */

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType
	 *
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String getContentType(String fileName) {
		String FilenameExtension = fileName.substring(fileName.lastIndexOf("."));
		if (FilenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equalsIgnoreCase("jpeg") || FilenameExtension.equalsIgnoreCase("jpg")
				|| FilenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (FilenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equalsIgnoreCase("pptx") || FilenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equalsIgnoreCase("docx") || FilenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}
}
